<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import AudioService from '../../services/AudioService';

// 定义props和emits
const props = defineProps({
  availableCharacters: {
    type: Array,
    default: () => [
      {
        id: 1,
        name: '鸣人',
        description: '木叶村的漩涡鸣人，九尾人柱力',
        image: '/naruto/naruto.png',
        health: 120,
        chakra: 100,
        strength: 85,
        skills: ['螺旋丸', '影分身之术', '仙人模式']
      },
      {
        id: 2,
        name: '佐助',
        description: '宇智波佐助，复仇者',
        image: '/naruto/sasuke.png',
        health: 110,
        chakra: 95,
        strength: 88,
        skills: ['千鸟', '豪火球之术', '写轮眼']
      },
      {
        id: 3,
        name: '小樱',
        description: '春野樱，医疗忍者',
        image: '/naruto/sakura.png',
        health: 90,
        chakra: 90,
        strength: 75,
        skills: ['樱花冲', '医疗忍术', '怪力']
      },
      {
        id: 4,
        name: '卡卡西',
        description: '旗木卡卡西，拷贝忍者',
        image: '/naruto/kakashi.png',
        health: 120,
        chakra: 100,
        strength: 90,
        skills: ['雷切', '写轮眼', '千年杀']
      }
    ]
  }
});

const emit = defineEmits(['character-select']);

// 响应式数据
const characters = ref(props.availableCharacters);
const selectedCharacter = ref(null);
const isLoading = ref(false);

// 角色选择函数
const selectCharacter = (character) => {
  try {
    // 防止重复点击
    if (isLoading.value || !character) return;
    
    isLoading.value = true;
    selectedCharacter.value = character;
    
    try {
      // 播放选择音效
      AudioService.playSound('select');
    } catch (audioError) {
      console.warn('播放选择音效失败，但选择过程继续:', audioError);
    }
    
    // 延迟发送选择结果，让音效有时间播放
    const timeoutId = setTimeout(() => {
      try {
        emit('character-select', character);
      } catch (emitError) {
        console.error('发送角色选择事件失败:', emitError);
      } finally {
        isLoading.value = false;
      }
    }, 500);
    
    // 保存timeoutID以便在组件卸载时清除
    window._characterSelectTimeout = timeoutId;
  } catch (error) {
    console.error('角色选择过程中发生错误:', error);
    isLoading.value = false;
    // 即使出错也要确保功能继续
    emit('character-select', character);
  }
};

onMounted(() => {
  // 初始化时重置状态
  selectedCharacter.value = null;
  isLoading.value = false;
  characters.value = props.availableCharacters;
  
  // 确保清理任何可能存在的超时
  if (window._characterSelectTimeout) {
    clearTimeout(window._characterSelectTimeout);
    window._characterSelectTimeout = null;
  }
});

onBeforeUnmount(() => {
  // 清理资源
  isLoading.value = false;
  
  // 清除任何未处理的超时
  if (window._characterSelectTimeout) {
    clearTimeout(window._characterSelectTimeout);
    window._characterSelectTimeout = null;
  }
});
</script>

<template>
  <div class="character-selection">
    <div class="character-grid">
      <div 
        v-for="character in characters" 
        :key="character.id" 
        class="character-card"
        :class="{ 'selected': selectedCharacter?.id === character.id, 'loading': isLoading }"
        @click="selectCharacter(character)"
      >
        <div class="character-image-container">
          <!-- 由于我们没有实际图片，使用占位符 -->
          <div class="character-placeholder">
            <div class="character-initials">{{ character.name.charAt(0) }}</div>
          </div>
        </div>
        <div class="character-info">
          <h3>{{ character.name }}</h3>
          <p class="character-description">{{ character.description }}</p>
          <div class="character-stats">
            <div class="stat">
              <span class="stat-label">生命值:</span>
              <span class="stat-value">{{ character.health }}</span>
            </div>
            <div class="stat">
              <span class="stat-label">查克拉:</span>
              <span class="stat-value">{{ character.chakra }}</span>
            </div>
            <div class="stat">
              <span class="stat-label">攻击力:</span>
              <span class="stat-value">{{ character.strength }}</span>
            </div>
          </div>
          <div class="character-skills">
            <p class="skills-label">技能:</p>
            <ul>
              <li v-for="(skill, index) in character.skills" :key="index">{{ skill }}</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.character-selection {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background: var(--naruto-bg);
  min-height: 100vh;
}

.title {
  font-size: 2.5rem;
  color: var(--naruto-red);
  margin-bottom: 30px;
  text-align: center;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
  font-weight: bold;
  letter-spacing: 1px;
  padding-bottom: 10px;
  border-bottom: 3px solid var(--naruto-orange);
  width: 100%;
  max-width: 600px;
}

.character-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 25px;
  width: 100%;
  max-width: 900px;
  margin-bottom: 30px;
}

.character-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 18px;
  padding: 25px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  border: 2px solid transparent;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.character-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, var(--naruto-red), var(--naruto-orange));
  transform: scaleX(0);
  transform-origin: left;
  transition: transform 0.3s ease;
}

.character-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
  border-color: var(--naruto-orange);
}

.character-card:hover::before {
  transform: scaleX(1);
}

.character-card.selected {
  transform: translateY(-8px);
  background: rgba(255, 153, 0, 0.05);
  border: 2px solid var(--naruto-orange);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
}

.character-card.selected::before {
  transform: scaleX(1);
}

.character-image-container {
  width: 100%;
  height: 200px;
  margin-bottom: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.character-placeholder {
  width: 160px;
  height: 160px;
  background: linear-gradient(45deg, var(--naruto-orange), var(--naruto-red));
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 3rem;
  font-weight: bold;
  color: white;
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.character-card:hover .character-placeholder {
  transform: scale(1.05) rotate(5deg);
}

.character-info {
  text-align: center;
}

.character-info h3 {
  margin: 0 0 15px 0;
  color: var(--naruto-red);
  font-size: 1.6rem;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.05);
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.character-description {
  margin: 0 0 15px 0;
  color: var(--naruto-text);
}

.character-stats {
  display: flex;
  justify-content: space-around;
  margin: 15px 0;
}

.stat {
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: color 0.3s ease;
}

.character-card:hover .stat {
  color: var(--naruto-orange);
}

.stat-label {
  font-size: 0.9rem;
  color: var(--naruto-text-light);
  font-weight: bold;
}

.stat-value {
  font-size: 1.2rem;
  font-weight: bold;
  color: var(--naruto-orange);
}

.character-skills {
  margin-top: 15px;
}

.skills-label {
  font-size: 1rem;
  font-weight: bold;
  margin: 0 0 10px 0;
  color: var(--naruto-orange);
}

.character-skills ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.character-skills li {
  background: rgba(255, 153, 0, 0.2);
  padding: 5px 10px;
  margin: 5px 0;
  border-radius: 5px;
  color: var(--naruto-text);
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.character-card {
  animation: fadeInUp 0.5s ease;
}

.character-card:nth-child(2) {
  animation-delay: 0.1s;
}

.character-card:nth-child(3) {
  animation-delay: 0.2s;
}

.character-card:nth-child(4) {
  animation-delay: 0.3s;
}

@media (max-width: 768px) {
  .character-grid {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .character-placeholder {
    width: 140px;
    height: 140px;
    font-size: 2.5rem;
  }
  
  .character-card {
    padding: 20px;
  }
}

@media (max-width: 480px) {
  .character-selection {
    padding: 15px;
  }
  
  .character-placeholder {
    width: 120px;
    height: 120px;
    font-size: 2rem;
  }
  
  .character-info h3 {
    font-size: 1.4rem;
  }
}
</style>